package com.lucenten.collect.exec;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * Shell脚本输入输出流
 */
@Slf4j
public class ShellStream extends Thread {
    private InputStream inputStream;
    private OutputStream outputStream;
    private String charset;
    private String type;
    public ShellStream(InputStream inputStream,String type) {
        this(inputStream,type,"GBK");
    }
    public ShellStream(InputStream inputStream,String type, String charset) {
        this(inputStream,null,type,"GBK");
    }
    public ShellStream(InputStream inputStream,OutputStream outputStream,String type,String charset) {
        this.inputStream = inputStream;
        this.outputStream = outputStream;
        this.type = type;
        this.charset = charset;
    }
    @Override
    public void run() {
        if (outputStream != null) {
            try (PrintWriter printWriter = new PrintWriter(outputStream);InputStreamReader reader = new InputStreamReader(inputStream,charset);BufferedReader bufferedReader = new BufferedReader(reader);){
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    printWriter.println(line);
                    log(line);
                }
            }catch (IOException e) {
                log.error("SHELL 命令执行失败："+e.toString(),e);
            }
            return;
        }
        try (InputStreamReader reader = new InputStreamReader(inputStream,charset);BufferedReader bufferedReader = new BufferedReader(reader);){
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                log(line);
            }
        }catch (IOException e) {
            log.error("SHELL 命令执行失败："+e.toString(),e);
        }
    }

    private void log(String line) {
        if ("error".equalsIgnoreCase(type)) {
            log.error("SHELL 调用失败 > "+line);
        }
    }
}
